package com.blogsoho.taurus.services.impl;

import com.blogsoho.taurus.dao.mapper.ContentMapper;
import com.blogsoho.taurus.services.AttachmentService;
import com.blogsoho.taurus.services.ContentService;
import com.blogsoho.taurus.vm.ContentViewModel;
import com.blogsoho.taurus.vm.ResponsePagerWrapper;
import com.blogsoho.taurus.vm.ResponseWrapper;
import com.blogsoho.taurus.vo.ContentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 16978 on 2017/6/10.
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private AttachmentService attachmentService;

    @Override
    public ResponseWrapper<?> addContent(ContentViewModel content) {
        ResponseWrapper<?> response = new ResponseWrapper<>();
        ContentVO vo = new ContentVO();
        BeanUtils.copyProperties(content, vo);
        boolean result = contentMapper.addContent(vo) > 0 ? true : false;
        attachmentService.addAttachmentMapping(content.getAttachmentId(), vo.getId());
        response.setSuccess(result);
        return response;
    }

    @Override
    public ResponsePagerWrapper<List<ContentVO>> getAllContent(int start, int length) {
        ResponsePagerWrapper<List<ContentVO>> response = new ResponsePagerWrapper<>();
        response.setData(contentMapper.getAllContent(start, length));
        int count = contentMapper.getCountContent();
        response.setRecordsTotal(count);
        response.setRecordsFiltered(count);
        return response;
    }

    @Override
    public ResponseWrapper<ContentVO> getContentById(int id) {
        ResponseWrapper<ContentVO> response = new ResponseWrapper<>();
        ContentVO content = contentMapper.getContentById(id);
        if (content != null) {
            response.setData(content);
        } else {
            response.setSuccess(false);
        }
        return response;
    }

    @Override
    public ResponseWrapper<?> updateContent(ContentViewModel content) {
        ResponseWrapper<?> response = new ResponseWrapper<>();
        ContentVO vo = new ContentVO();
        BeanUtils.copyProperties(content, vo);
        boolean result = contentMapper.updateContent(vo) > 0 ? true : false;
        response.setSuccess(result);
        return response;
    }

    @Override
    public ResponseWrapper<List<ContentVO>> getContentByCategoryId(int id) {
        ResponseWrapper<List<ContentVO>> response = new ResponseWrapper<List<ContentVO>>();
        response.setData(contentMapper.getContentByCategoryId(id));
        return response;
    }
}
